package com.thwj.project.app.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.thwj.project.biz.domain.UserVip;
import com.thwj.project.biz.enums.UserVipStatusEnum;
import com.thwj.project.biz.service.IUserVipService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Copyright (C), 
 *
 * @author: 可乐
 * @date: 2019/06/04 14:01
 * @description:
 */
@Component
public class UserVipResolver {


    @Autowired
    private IUserVipService userVipService;

    /**
     * @param targetList 需要补全的对象列表
     * @param getUserId  每个对象获取用户id的方法
     * @param resolver   对每个对象赋值的回调方法
     * @param <T>
     */
    public <T> void resolve(List<T> targetList, Function<T, Long> getUserId, InfoOnlyResolve<T> resolver) {
        List<Long> userIdList = targetList.stream().map(getUserId).filter(i -> null != i).distinct().collect(Collectors.toList());
        if(CollectionUtils.isEmpty(userIdList)) {
            return;
        }
        List<UserVip> userVipList = userVipService.list(new QueryWrapper<UserVip>()
                .in("user_id",userIdList)
                .eq("status", UserVipStatusEnum.working.getValue())
        );
        targetList.forEach(i -> {
            if(getUserId.apply(i) != null) {
                List<UserVip> userListOne = userVipList.stream().filter(DO->DO.getUserId().compareTo(getUserId.apply(i)) == 0).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(userListOne)) {
                    resolver.resolve(i, true);
                }else {
                    resolver.resolve(i, false);
                }

            }
        });
    }
    /**
     * @param target 需要补全的对象列表
     * @param getUserId  每个对象获取用户id的方法
     * @param resolver   对每个对象赋值的回调方法
     * @param <T>
     */
    public <T> void resolve(T target, Function<T, Long> getUserId, InfoOnlyResolve<T> resolver) {
        UserVip userVip = userVipService.getOne(new QueryWrapper<UserVip>()
                .eq("user_id",getUserId.apply(target))
                .eq("status", UserVipStatusEnum.working.getValue())
                .orderByDesc("create_date")
        );
        if(userVip == null) {
            resolver.resolve( target, false);
        }else {
            resolver.resolve( target, true);
        }

    }
    public interface InfoOnlyResolve<T> {
        void resolve(T obj, boolean vipOrNot);
    }

}
